/*
 * SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

use std::fs::{read_to_string, File};
#[allow(unused_imports)]
use std::io::{Read, Write};
#[allow(unused_imports)]
use std::process::{Command, Stdio};
use tempfile::tempdir;

#[test]
fn test_utzipnote_edit_comment_file() {
    let dir = tempdir().unwrap();
    let zip_path = dir.path().join("note.zip");
    let file_path = dir.path().join("notefile.txt");
    let mut file = File::create(&file_path).unwrap();
    writeln!(file, "note test").unwrap();

    // 创建zip
    let status = Command::new("./target/debug/utzip")
        .arg(&zip_path)
        .arg(&file_path)
        .status()
        .unwrap();
    assert!(status.success());

    // 导出注释到注释.txt
    let comment_txt = dir.path().join("注释.txt");
    let mut child = Command::new("./target/debug/utzipnote")
        .arg(&zip_path)
        .stdout(File::create(&comment_txt).unwrap())
        .spawn()
        .unwrap();
    assert!(child.wait().unwrap().success());

    // 编辑注释.txt
    let mut content = read_to_string(&comment_txt).unwrap();
    // 这里假设注释格式为 "@ 文件名\n原注释内容\n" 或 "@ (archive comment)\n原注释内容\n"
    // 你可以根据实际格式替换

    content = content.replace("@ (comment above this line)", "This is a new comment!");
    std::fs::write(&comment_txt, content).unwrap();

    // 写回注释
    let mut child = Command::new("./target/debug/utzipnote")
        .arg("-w")
        .arg(&zip_path)
        .stdin(File::open(&comment_txt).unwrap())
        .spawn()
        .unwrap();
    assert!(child.wait().unwrap().success());

    // 再次导出，检查注释已更新
    let output = Command::new("./target/debug/utzipnote")
        .arg(&zip_path)
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("This is a new comment!"));
}
